package com.fivefu.core.hillstone.services.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fivefu.base.common.utils.DateUtils;
import com.fivefu.base.common.utils.str.StrUtils;
import com.fivefu.core.hillstone.dto.request.PlayBackURIDto;
import com.fivefu.core.hillstone.dto.request.RealTimeMonitorURIDto;
import com.fivefu.core.hillstone.entity.DbHillstoneChannel;
import com.fivefu.core.hillstone.mapper.DbHillstoneChannelMapper;
import com.fivefu.core.hillstone.services.DbHillstoneChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fivefu.core.hillstone.services.HillstoneService;
import com.fivefu.module.dictionary.entity.DbSysDict;
import com.fivefu.module.dictionary.service.DbSysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 大华通道表 服务实现类
 * </p>
 *
 * @author 
 * @since 2022-08-23 15:26:08
 */
@Service
public class DbHillstoneChannelServiceImpl extends ServiceImpl<DbHillstoneChannelMapper, DbHillstoneChannel> implements DbHillstoneChannelService {

    @Autowired
    private HillstoneService hillstoneService;

    @Autowired
    private DbSysDictService dbSysDictService;

    /**
     * 通过通道编码查询通道信息
     * @param channelCode     通道编码
     * @return
     */
    public DbHillstoneChannel queryHillstoneChannel(String channelCode) {
        QueryWrapper<DbHillstoneChannel> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.eq("channel_code",channelCode);
        DbHillstoneChannel channel = baseMapper.selectOne(wrapper);
        return channel;
    }


    /**
     * 编辑通道信息
     * @param channel
     */
    @Override
    public void editDbHillstoneChannel(DbHillstoneChannel channel) {
        LocalDateTime time = LocalDateTime.now();
        DbHillstoneChannel oldChannel = queryHillstoneChannel(channel.getChannelCode());
        channel.setUpdatedBy("sys");
        channel.setUpdatedTime(time);

        //判断通道类型是否为空
        if (StrUtils.isNotNull(channel.getChannelType())) {
            DbSysDict dict = dbSysDictService.queryDictByValue("CH", channel.getChannelType());
            if (null != dict) {
                channel.setChannelType(dict.getDictCode());
            }
        }
        //判断所属单元类型是否为空
        if (StrUtils.isNotNull(channel.getUnitType())) {
            DbSysDict dict = dbSysDictService.queryDictByValue("DYLX", channel.getUnitType());
            if (null != dict) {
                channel.setUnitType(dict.getDictCode());
            }
        }
        //判断是否已经存在相关信息数据
        if (null != oldChannel) {
            channel.setId(oldChannel.getId());
            baseMapper.updateById(channel);
        } else {
            channel.setCreatedBy("sys");
            channel.setCreatedTime(time);
            channel.setIsDelete(0);
            baseMapper.insert(channel);
        }

    }

    /**
     * 获取实时监视URI
     * @param channelCode 通道编码
     * @param subType 码流类型(0:主码流、1:辅流1、2:辅流2。默认为0主码流)
     * @param scheme 协议类型(本级平台支持RTSP、FLV_HTTP、HLS、RTMP四种，下级平台只支持RTSP。默认RTSP
     */
    @Override
    public JSONObject getRealTimeMonitoringURI(String channelCode, Integer subType, String scheme) {
        RealTimeMonitorURIDto monitorURIDto = new RealTimeMonitorURIDto();
        monitorURIDto.setChannelId(channelCode);
        if (subType != null) {
            monitorURIDto.setSubType(subType);
        }
        if (StrUtils.isNotNull(scheme)) {
            monitorURIDto.setScheme(scheme);
        }

        String result = hillstoneService.getHillstone("/videoService/realmonitor/uri" + monitorURIDto.getParam());
        if (StrUtils.isNotNull(result) && !result.equals("error")) {
            JSONObject resultObj = JSON.parseObject(result);
            return resultObj;
            //视频地址格式       返回无此字段
            //String transmode = resultObj.getString("transmode");
            //返回结果中的load字段
            //String load = resultObj.getString("load");
        }
        return null;
    }

    /**
     * 删除本地多余通道数据
     * @param channelCode    通道编码
     */
    @Override
    public void deleteRedundantData(String channelCode) {
        LocalDateTime time = LocalDateTime.now();
        List<DbHillstoneChannel> channelList = queryChannelList(channelCode);

        //判断是否已经存在相关数据信息
        if (null != channelList && channelList.size() > 0) {
            List<Long> idList = channelList.stream().map(k -> k.getId()).collect(Collectors.toList());
            Map<String, Long> channelMap = channelList.stream().collect(Collectors.toMap(k -> k.getChannelCode(), v -> v.getId()));
            if (StrUtils.isNotNull(channelCode)) {
                if (channelMap.containsKey(channelCode)) {
                    Long id = channelMap.get(channelCode);
                    idList.remove(id);
                }
            }

            //删除多余通道数据
            if (idList.size() >0 ) {
                DbHillstoneChannel channel = new DbHillstoneChannel();
                channel.setIsDelete(1);
                channel.setUpdatedBy("sys");
                channel.setUpdatedTime(time);

                QueryWrapper<DbHillstoneChannel> wrapper = new QueryWrapper<>();
                wrapper.in("id",idList);
                wrapper.eq("is_delete",0);
                wrapper.eq("channel_code",channelCode);
                baseMapper.update(channel,wrapper);
            }
        }
    }

    /**
     * 根据通道编码查询相关数据集
     * @param channelCode
     * @return
     */
    @Override
    public List<DbHillstoneChannel> queryChannelList(String channelCode) {
        QueryWrapper<DbHillstoneChannel> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.eq("channel_code",channelCode);
        List<DbHillstoneChannel> channelList = baseMapper.selectList(wrapper);
        return channelList;
    }

    /**
     * 获取本地通道表所有数据信息
     * @return
     */
    @Override
    public List<DbHillstoneChannel> queryAllChannel() {
        QueryWrapper<DbHillstoneChannel> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        List<DbHillstoneChannel> channelList = baseMapper.selectList(wrapper);
        return channelList;
    }

    /**
     * 获取回放URI
     * @param channelCode     通道编码
     * @param beginTime       回放开始时间  YYYYMMDDTHHmmssZ
     * @param endTime         回放结束时间  YYYYMMDDTHHmmssZ
     * @param location        录像存储位置(cloud:平台录像，device:设备录像（不要使用）)
     * @param scheme          协议类型，支持RTSP、RTMP、HLS三种。默认RTSP
     * @param duration        有效时间，单位为秒，最长不超过10分钟，默认10分钟
     * @return
     */
    @Override
    public JSONObject getPlaybackURI(String channelCode, String beginTime, String endTime, String location, String scheme, Integer duration) {
        PlayBackURIDto playBackURIDto = new PlayBackURIDto();
        playBackURIDto.setChannelCode(channelCode);
        playBackURIDto.setBeginTime(formatData(beginTime));
        playBackURIDto.setEndTime(formatData(endTime));
        playBackURIDto.setLocation(location);
        if (StrUtils.isNotNull(scheme)) {
            playBackURIDto.setScheme(scheme);
        }
        if (null != duration) {
            playBackURIDto.setDuration(duration);
        }

        String result = hillstoneService.getHillstone("/videoService/playback/uri" + playBackURIDto.getParam());
        if (StrUtils.isNotNull(result) && !result.equals("error")) {
            JSONObject resultObj = JSON.parseObject(result);
            return resultObj;
        }
        return null;
    }

    /**
     * 根据通道编码查询通道信息
     * @param channelCode      通道编码
     * @return
     */
    @Override
    public DbHillstoneChannel queryChannelByCode(String channelCode) {
        QueryWrapper<DbHillstoneChannel> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.eq("channel_code",channelCode);
        return baseMapper.selectOne(wrapper);
    }

    /**
     * 将字符串时间yyyy-MM-dd HH:mm:ss 转换为字符串YYYYMMDDTHHmmssZ
     * @param time
     * @return
     */
    public String formatData(String time) {
        return time.replace("-","").replace(":","").replace(" ","T") + "Z";
    }
}
